//
//  TL_Login_ViewController.m
//  WXReader
//
//  Created by LL on 2020/8/18.
//  Copyright © 2020 Andrew. All rights reserved.
//

#import "TL_LoginViewController.h"
#import "TL_LoginDetailViewController.h"
#import "TL_AppleSignManager.h"
#import "TL_GoogleManager.h"
#import "TL_FacebookManager.h"
#import "TL_WebViewViewController.h"
#import "AppDelegate.h"
//#import "TL_AppsFlyerManager.h"

@interface TL_LoginViewController ()<TL_GoogleManagerDelegate, TL_AppleSignManagerDelegate, TL_FacebookManagerDelegate>

@property (nonatomic, copy) void(^_Nullable completeBlock)(TL_LoginViewController *vc);

@property (nonatomic, strong) UIView *fkLoginView;

@property (nonatomic, strong) UIView *glView;

@property (nonatomic, strong) UIView *mlView;

@property (nonatomic, strong) UIView *alView;

@end

@implementation TL_LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initialize];
    [self createSubviewsFunc];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setStatusBarDefaultStyle];
    
    self.navigationController.navigationBar.hidden = YES;
}

+ (void)presentLoginView:(void (^)(TL_UserInfoModel * _Nonnull))complete {
    TL_LoginViewController *vc = [[TL_LoginViewController alloc] init];
    vc.completeBlock = ^(TL_LoginViewController *vc) {
        !complete ?: complete(TL_UserInfoModel.shareInstance);
    };
    NavigationController *nav = [[NavigationController alloc] initWithRootViewController:vc];
    [[TL_ViewHelper getCurrentViewController] presentViewController:nav animated:YES completion:nil];
}

+ (void)insterestPresentLoginView {
    TL_LoginViewController *vc = [[TL_LoginViewController alloc] init];
    vc.isShowSkip = YES;
    vc.completeBlock = ^(TL_LoginViewController *vc) {
    };
    NavigationController *nav = [[NavigationController alloc] initWithRootViewController:vc];
    [[TL_ViewHelper getCurrentViewController] presentViewController:nav animated:YES completion:nil];
}

#pragma mark - 初始化
- (void)initialize {
    [self setNavigationBarBackgroundColor:[UIColor clearColor]];
    [self setNavigationBarTintColor:kBlackColor];
    [self hiddenNavigationBarLeftButton];
    [self.view addGradientBackground];

    UIButton *closeButton = [TL_UIFactory buttonWithTarget:self action:@selector(closeActionEvent)];
    closeButton.frame = CGRectMake(22, PUB_NAVBAR_OFFSET + 20, 44, 44);
    closeButton.imageEdgeInsets = UIEdgeInsetsMake(12, 12, 12, 12);
    [closeButton setImage:[UIImage imageNamed:@"public_close"] forState:UIControlStateNormal];
    closeButton.tintColor = kBlackColor;
    [self setNavigationBarRightButton:closeButton];
     
    [TL_GoogleManager sharedManager].delegate = self;
    [TL_AppleSignManager sharedManager].delegate = self;
    [TL_FacebookManager sharedManager].delegate = self;
}

- (void)closeActionEvent {

    [self dismissViewControllerAnimated:YES completion:^{
//        [[TL_AppsFlyerManager sharedInstance] deeplinkEvent];

        if (!TL_UserInfoManager.isLogin) return;
        !self.completeBlock ?: self.completeBlock(self);

        [[NSNotificationCenter defaultCenter] postNotificationName:Notification_Login_Success object:TL_UserInfoModel.shareInstance];
 
    }];
}
- (void)skipActionEvent {
    MK_WEAK_SELF
    
    [APIManager sendPostRequest:[APIURLManager Tourists_Login] parameters:@{@"udid":[TL_UtilsHelper getUDID]} model:TL_UserInfoModel.class success:^(BOOL success, TL_UserInfoModel*  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        if (responseData.is_new) {
//            [TL_AnalyticsManager logEvent:@"registration" params:@{}];
        }
        [weakSelf closeActionEvent];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [weakSelf closeActionEvent];
    }];
    
}

- (void)closeActionView {

    [self dismissViewControllerAnimated:YES completion:^{
//        [[TL_AppsFlyerManager sharedInstance] deeplinkEvent];

        if (!TL_UserInfoManager.isLogin) return;
        !self.completeBlock ?: self.completeBlock(self);

        [[NSNotificationCenter defaultCenter] postNotificationName:Notification_Login_Success object:TL_UserInfoModel.shareInstance];
        [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeSuccess alertTitle:WXLocalizedString(@"登录成功")];
    }];
}

#pragma mark - UI创建
- (void)createSubviewsFunc {
    UIScrollView *mainScrollView = [TL_UIFactory scrollView];
    mainScrollView.showsVerticalScrollIndicator = YES;
    [self.view addSubview:mainScrollView];
    
    [mainScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.navigationBar.mas_bottom);
        make.left.right.mas_equalTo(0);
    }];
    
    UIView *contentView = [[UIView alloc] init];
    [mainScrollView addSubview:contentView];
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.width.equalTo(mainScrollView);
    }];
    
    UIImageView *iconImageView = [TL_UIFactory imageView];
    iconImageView.layer.cornerRadius = 22;
    iconImageView.image = [UIImage imageNamed:[TL_ViewHelper getIconImageName]];
    [contentView addSubview:iconImageView];
    [iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(contentView).offset(kGeometricWidth(kScreenHeight, 80.0, 667.0));
        make.width.height.mas_equalTo(109);
        make.centerX.mas_equalTo(contentView);
    }];
    
    UILabel *appNameLabel = [TL_UIFactory labelWithBackgroundColor:nil font:BOLD_SYSTEM_FONT(16) textColor:[UIColor hex_9E6DFC]];
    appNameLabel.text = App_Name;
    [contentView addSubview:appNameLabel];
    
    [appNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(iconImageView.mas_bottom).offset(28);
        make.centerX.mas_equalTo(contentView);
    }];

    UILabel *introLabel = [TL_UIFactory labelWithBackgroundColor:nil font:SYSTEM_FONT(16) textColor:[UIColor hex_333333]];
    introLabel.text = WXLocalizedString(@"触摸故事，每分钟都有新奇");
    introLabel.numberOfLines = 0;
    introLabel.textAlignment = NSTextAlignmentCenter;
    introLabel.preferredMaxLayoutWidth = kScreenWidth - 2 * 40.0;
    [contentView addSubview:introLabel];
    [introLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(appNameLabel.mas_bottom).offset(20);
        make.left.right.equalTo(contentView).inset(40.0);
        make.height.mas_equalTo(introLabel.w_textHeight);
    }];
    
    CGFloat loginButtonHeigth = 45.0;
    
    self.alView.layer.cornerRadius = loginButtonHeigth / 2.0;
    [contentView addSubview:self.alView];
    
    [self.alView mas_makeConstraints:^(MASConstraintMaker *make) {
        if (IS_IPHONE_X) {
            make.top.equalTo(introLabel.mas_bottom).offset(kGeometricWidth(kScreenHeight, 60.0, 667.0));
        } else {
            make.top.mas_equalTo(introLabel.mas_bottom).offset(10);
        }
        make.left.right.equalTo(contentView).inset(40.0);
        make.height.mas_equalTo(loginButtonHeigth);
    }];
    
    self.glView.layer.cornerRadius = loginButtonHeigth / 2.0;
    [contentView addSubview:self.glView];
    [self.glView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.alView.mas_bottom).offset(kHalfMargin);
        make.left.right.equalTo(contentView).inset(40.0);
        make.height.mas_equalTo(loginButtonHeigth);
    }];
    
    self.fkLoginView.layer.cornerRadius = self.glView.layer.cornerRadius;
    [contentView addSubview:self.fkLoginView];
    [self.fkLoginView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.glView.mas_bottom).offset(kHalfMargin);
        make.left.right.height.mas_equalTo(self.glView);
    }];
    
    self.mlView.layer.cornerRadius = self.fkLoginView.layer.cornerRadius;
    [contentView addSubview:self.mlView];
    
    [self.mlView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.fkLoginView.mas_bottom).offset(kHalfMargin);
        make.left.right.height.mas_equalTo(self.fkLoginView);
        make.bottom.mas_equalTo(0);
    }];

 
    YYLabel *protocolLabel = [[YYLabel alloc] init];
    protocolLabel.font = SYSTEM_FONT(12);
    protocolLabel.textColor = [UIColor hex_333333];
    protocolLabel.preferredMaxLayoutWidth = kScreenWidth - kLabelHeight * 2;
    protocolLabel.numberOfLines = 0;

    NSString *prefix = WXLocalizedString(@"点击登录即表示已同意");
    NSString *app_name = [NSString stringWithFormat:@"「%@」", App_Name];
    NSString *userProtocol = [NSString stringWithFormat:@"\r<%@>", WXLocalizedString(@"用户协议")];
    NSString *privacyProtocl = [NSString stringWithFormat:@"<%@>", WXLocalizedString(@"隐私政策")];
    
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%@%@%@", prefix, app_name, userProtocol, privacyProtocl] attributes:@{NSFontAttributeName : protocolLabel.font, NSForegroundColorAttributeName : protocolLabel.textColor}];
    text.lineSpacing = kQuarterMargin;
    text.alignment = NSTextAlignmentCenter;

    NSRange userProtocolRange = NSMakeRange(prefix.length + app_name.length, userProtocol.length);
    NSRange privacyProtoclRange = NSMakeRange(NSMaxRange(userProtocolRange), privacyProtocl.length);
    
    MK_WEAK_SELF;

    [text setTextHighlightRange:userProtocolRange color:kMainColor backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {

        TL_WebViewViewController *vc = [[TL_WebViewViewController alloc] init];
        vc.isPresentState = NO;
        vc.navTitle = WXLocalizedString(@"用户协议");
        vc.URLString = [NSString stringWithFormat:@"%@",[APIURLManager AgreementURL]];
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    [text setTextHighlightRange:privacyProtoclRange color:kMainColor backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {

        TL_WebViewViewController *vc = [[TL_WebViewViewController alloc] init];
        vc.isPresentState = NO;
        vc.navTitle = WXLocalizedString(@"隐私政策");
        vc.URLString = [NSString stringWithFormat:@"%@",[APIURLManager PrivacyURL]];
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];

    protocolLabel.attributedText = text;
    [self.view addSubview:protocolLabel];
    
    YYTextLayout *textLayout = [YYTextLayout layoutWithContainerSize:CGSizeMake(protocolLabel.preferredMaxLayoutWidth, CGFLOAT_MAX) text:text];
    [protocolLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view).inset(40.0);
        make.bottom.equalTo(self.view).offset(-PUB_TABBAR_OFFSET - kMargin);
        make.height.mas_equalTo(textLayout.textBoundingSize.height);
    }];
    
    [mainScrollView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(protocolLabel.mas_top).offset(-kHalfMargin);
    }];
    
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.width.equalTo(mainScrollView);
        make.bottom.equalTo(self.mlView.mas_bottom); // 确保最后一个子视图底部对齐
    }];
    
    [contentView layoutIfNeeded];
}

- (UIView *)fkLoginView {
    if (_fkLoginView == nil) {
        _fkLoginView = [TL_UIFactory view];
        _fkLoginView.layer.borderWidth = 1;
        _fkLoginView.layer.borderColor = [UIColor hex_ECECEC].CGColor;
        [_fkLoginView setBackgroundColor:[UIColor whiteColor]];
        
        UIButton *facebookButton = [TL_UIFactory buttonTypeCustomWithFont:kMainFont textColor:kBlackColor target:self action:@selector(facebookEvent)];
        [facebookButton setTitle:WXLocalizedString(@"Facebook") forState:UIControlStateNormal];
        [_fkLoginView addSubview:facebookButton];
        
        [facebookButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(_fkLoginView);
        }];
        
        UIImageView *facebookImageView = [TL_UIFactory imageView];
        facebookImageView.image = [UIImage imageNamed:@"public_facebook"];
        [_fkLoginView addSubview:facebookImageView];
        
        [facebookImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.mas_equalTo(24.0);
            make.left.mas_equalTo(_fkLoginView).offset(kMoreHalfMargin);
            make.centerY.mas_equalTo(_fkLoginView);
        }];
    }
    return _fkLoginView;
}

- (void)facebookEvent {
    [[TL_FacebookManager sharedManager] tunedUpFacebookWithState:TL_FacebookStateLogin];
}

- (UIView *)glView {
    if (_glView == nil) {
        _glView = [TL_UIFactory view];
        _glView.layer.borderWidth = 1;
        _glView.layer.borderColor = [UIColor hex_ECECEC].CGColor;
        [_glView setBackgroundColor:[UIColor whiteColor]];
        
        UIButton *googleButton = [TL_UIFactory buttonTypeCustomWithFont:kMainFont textColor:kBlackColor target:self action:@selector(googleEventFunc)];
        [googleButton setTitle:WXLocalizedString(@"Google") forState:UIControlStateNormal];
        [_glView addSubview:googleButton];
        
        [googleButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(0);
        }];
        
        UIImageView *googleImageView = [TL_UIFactory imageView];
        googleImageView.image = [UIImage imageNamed:@"public_google"];
        [_glView addSubview:googleImageView];
        
        [googleImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.mas_equalTo(kMargin);
            make.left.mas_equalTo(_glView).offset(kMoreHalfMargin);
            make.centerY.mas_equalTo(_glView);
        }];
    }
    return _glView;
}

- (void)googleEventFunc {
    [[TL_GoogleManager sharedManager] tunedUpGoogleWithState:TL_GoogleStateLogin];
}

- (UIView *)mlView {
    if (_mlView == nil) {
        _mlView = [TL_UIFactory view];
        _mlView.layer.borderWidth = 1;
        _mlView.layer.borderColor = [UIColor hex_ECECEC].CGColor;
        [_mlView setBackgroundColor:[UIColor whiteColor]];
        
        UIButton *mailboxButton = [TL_UIFactory buttonTypeCustomWithFont:kMainFont textColor:kBlackColor target:self action:@selector(mailboxEventFunc)];
        [mailboxButton setTitle:WXLocalizedString(@"邮箱登录") forState:UIControlStateNormal];
        [_mlView addSubview:mailboxButton];
        
        [mailboxButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(0);
        }];
        
        UIImageView *mailboxImageView = [TL_UIFactory imageView];
        mailboxImageView.image = [UIImage imageNamed:@"public_mailbox"];
        mailboxImageView.backgroundColor = UIColor.clearColor;
        [_mlView addSubview:mailboxImageView];
        
        [mailboxImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.mas_equalTo(24.0);
            make.left.mas_equalTo(_mlView).offset(kMoreHalfMargin);
            make.centerY.mas_equalTo(_mlView);
        }];
    }
    return _mlView;
}

- (void)mailboxEventFunc {
    MK_WEAK_SELF
    TL_LoginDetailViewController *loginDetailViewController = [[TL_LoginDetailViewController alloc] init];
    [[TL_ViewHelper getCurrentViewController].navigationController pushViewController:loginDetailViewController animated:YES];
    loginDetailViewController.closeBlock = ^{
        [weakSelf closeActionView];
    };
}

- (UIView *)alView {
    if (_alView == nil) {
        _alView = [TL_UIFactory view];
        _alView.layer.borderWidth = 1;
        _alView.layer.borderColor = [UIColor hex_ECECEC].CGColor;
        [_alView setBackgroundColor:[UIColor whiteColor]];
      
        UIButton *appLoginButton = [TL_UIFactory buttonTypeCustomWithFont:kMainFont textColor:kBlackColor target:self action:@selector(appleLoginEventFunc)];
        [appLoginButton setTitle:WXLocalizedString(@"Sign in with Apple") forState:UIControlStateNormal];
        [_alView addSubview:appLoginButton];
        
        [appLoginButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(0);
        }];
        
        UIImageView *appLoginImageView = [TL_UIFactory imageView];
        appLoginImageView.image = [UIImage imageNamed:@"public_apple"];
        [_alView addSubview:appLoginImageView];
        
        [appLoginImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.mas_equalTo(24.0);
            make.left.mas_equalTo(_alView).offset(kMoreHalfMargin);
            make.centerY.mas_equalTo(_alView);
        }];
    }
    return _alView;
}

- (void)appleLoginEventFunc {
    if (@available(iOS 13.0, *)) {
        [[MKAppleLoginUtils sharedInstance] authWithSuperView:self.view success:^(MKAppleLoginModel * _Nonnull info) {
            
            NSMutableDictionary *tParam = @{}.mutableCopy;
            tParam = [[info mj_keyValues] mutableCopy];
            
            [APIManager sendPostRequest:[APIURLManager appleLogin] parameters:tParam model:nil success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
                if (success) {
                    
                    TL_UserInfoModel *usermodel = [TL_UserInfoModel mj_objectWithKeyValues:requestModel.data[@"userInfo"]];
                    NSString *token = requestModel.data[@"token"];
                    
                    NSLog(@"user token: %@",token);
                    
                    [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"userToken"];
                    
                    NSDictionary *userDataDict = [usermodel mj_keyValues];
                    
                    [[NSUserDefaults standardUserDefaults] setObject:userDataDict forKey:@"UserInfoModelDict"];
                    
                    [self closeActionEvent];
                    
                }else{
                    [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:requestModel.msg];
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                    [TL_TopAlertManager showAlertWithError:error defaultText:nil];
            }];
        } failure:^(NSInteger code, NSString * _Nonnull message) {
            [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:message];
        }];
        
    }
}

#pragma mark TL_AppleSignManagerDelegate
- (void)appleSignResponseSuccess:(TL_UserInfoModel *)userData {
    [self closeActionView];
}

- (void)appleSignResponseFail:(NSString *)error {
    [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:error ?: WXLocalizedString(@"登录失败")];
}

#pragma mark TL_GoogleManagerDelegate
- (void)googleLoginSuccess:(TL_GoogleManager *)manager userInfo:(TL_UserInfoModel *)userInfo {
    
    [[NSUserDefaults standardUserDefaults] setObject:userInfo.token forKey:@"userToken"];
    
    NSDictionary *userDataDict = [userInfo mj_keyValues];
    
    [[NSUserDefaults standardUserDefaults] setObject:userDataDict forKey:@"UserInfoModelDict"];
    
    [self closeActionView];
}

- (void)googleLoginFail:(TL_GoogleManager *)manager error:(NSString *)error {
    [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:error ?: WXLocalizedString(@"登录失败")];
}

#pragma mark TL_FacebookManagerDelegate
- (void)facebookLoginSuccess:(TL_FacebookManager *)manager userInfo:(TL_UserInfoModel *)userInfo {
    [self closeActionView];
}

- (void)facebookLoginFail:(TL_FacebookManager *)manager error:(NSString *)error {
    [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:error ?: WXLocalizedString(@"登录失败")];
}

@end
